//
// Created by HP on 2025/11/28.
//
#include "../include/Headler.h"
#include "../model/Ticket.h"
#include "../model/Order.h"
#include "../model/User.h"
#include "../model/Game.h"
#include "../include/jwt.h"
#include "../model/Notification.h"
#include <sstream>
#include <algorithm>

// type Request struct {
// 	// 分类筛选，有“全部分类”，“角色扮演”，“动作冒险”，"策略","模拟"       
// 	Category                               string `json:"category"`
// 	// 搜索关键词，用于搜索游戏标题等信息                          
// 	Keyword                                string `json:"keyword"`
// 	// 页码，从1开始                                    
// 	Page                                   string `json:"page"`
// 	// 每页显示数量，有10,20,50keyword                    
// 	PageSize                               string `json:"pageSize"`
// 	// 状态筛选（"未发布"、"已发布"、"已下架"、"全部"）               
// 	Status                                 string `json:"status"`
// }


// type Response struct {
// 	Data       Data  `json:"data"`
// 	StatusCode int64 `json:"StatusCode"`
// 	Success    bool  `json:"success"`
// }

// type Data struct {
// 	List  []List `json:"list"`
// 	Total int64  `json:"total"`
// }

// type List struct {
// 	Category    string `json:"category"`
// 	ID          string `json:"id"`
// 	PublishDate string `json:"publishDate"`
// 	Status      string `json:"status"`
// 	Title       string `json:"title"`
// }

void getGameContent(const Request& req, Response& res) {
    if (! Middleware::requiredContent(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
//    std::cout<<"1"<<std::endl;
    // 获取查询参数
    std::string category = req.query_param("category");
    std::string keyword = req.query_param("keyword");
    std::string page = req.query_param("page");
    std::string pageSize = req.query_param("pageSize");
    std::string status = req.query_param("status");

    // 设置默认分页参数
    int pageNum = 1;
    int pageSizeNum = 10;
    
    // 解析页码参数
    if (!page.empty()) {
        try {
            pageNum = std::stoi(page);
            if (pageNum < 1) pageNum = 1;
        } catch (...) {
            pageNum = 1;
        }
    }
    
    // 解析每页数量参数（支持10,20,50）
    if (!pageSize.empty()) {
        try {
            pageSizeNum = std::stoi(pageSize);
            if (pageSizeNum != 10 && pageSizeNum != 20 && pageSizeNum != 50) {
                pageSizeNum = 10;
            }
        } catch (...) {
            pageSizeNum = 10;
        }
    }
    
    int offset = (pageNum - 1) * pageSizeNum;
    
    // 构建SQL查询条件
    std::string sqlConditions = "1=1";
    
    // 分类筛选
    if (!category.empty() && category != "全部分类") {
        sqlConditions += " AND role = '" + Model::escapeSqlLiteral(category) + "'";
    }
    
    // 关键词搜索
    if (!keyword.empty()) {
        sqlConditions += " AND title LIKE '%" + Model::escapeSqlLiteral(keyword) + "%'";
    }
    
    // 状态筛选
    if (!status.empty() && status != "全部") {
        if (status == "已发布") {
            sqlConditions += " AND status = 'published'";
        } else if (status == "未发布") {
            sqlConditions += " AND status = 'draft'";
        } else if (status == "已下架") {
            sqlConditions += " AND status = 'unpublished'";
        }
    }
    
    // 获取总数
    std::string countSql = "SELECT COUNT(*) AS total FROM games WHERE " + sqlConditions + ";";
    auto countResult = DBConnector::getInstance()->query(countSql);
    int total = 0;
    if (!countResult.empty()) {
        try {
            total = std::stoll(countResult[0]["total"]);
        } catch (...) {
            total = 0;
        }
    }
    
    // 获取分页数据
    std::string sql = "SELECT id, title, role AS Category, status, publicTime AS PublishDate "
                    "FROM games WHERE " + sqlConditions + 
                    " ORDER BY createdAt DESC LIMIT " + std::to_string(pageSizeNum) + 
                    " OFFSET " + std::to_string(offset) + ";";
    
    auto result = DBConnector::getInstance()->query(sql);
    
    // 构建响应数据
    std::vector<JsonValue> list;
    for (auto& row : result) {
        std::map<std::string, JsonValue> item;
        if (row.count("id")) item["ID"] = JsonValue(row["id"]);
        if (row.count("title")) item["Title"] = JsonValue(row["title"]);
        if (row.count("Category")) item["Category"] = JsonValue(row["Category"]);
        
        // 转换状态显示
        if (row.count("status")) {
            std::string statusText = row["status"];
            if (statusText == "published") statusText = "已发布";
            else if (statusText == "draft") statusText = "未发布";
            else if (statusText == "unpublished") statusText = "已下架";
            item["Status"] = JsonValue(statusText);
        }
        
        if (row.count("PublishDate")) item["PublishDate"] = JsonValue(row["PublishDate"]);
        list.push_back(JsonValue(item));
    }
    
    // 构建嵌套的响应结构
    std::map<std::string, JsonValue> data;
    data["list"] = JsonValue(list);
    data["total"] = JsonValue(total);
    
    std::map<std::string, JsonValue> resMp;
    resMp["Data"] = JsonValue(data);
    resMp["StatusCode"] = JsonValue(200);
    resMp["Success"] = JsonValue(true);
    
    res.json(toJson(resMp));
}

//type Request struct {
//    // 游戏分类（角色扮演、动作冒险、策略、模拟）
//    Category                string  `json:"category"`
//    // 游戏描述信息
//    Description             *string `json:"description,omitempty"`
//    // 发布日期（格式：YYYY-MM-DD）
//    PublishDate             string  `json:"publishDate"`
//    // 内容状态（"已发布"、"草稿"）
//    Status                  string  `json:"status"`
//    // 游戏标题
//    Title                   string  `json:"title"`
//}

//type Response struct {
//    StatusCode int64 `json:"StatusCode"`
//    Success    bool  `json:"success"`
//}

void addGameContent(const Request& req, Response& res) {
    if (! Middleware::requiredContent(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    try {
        // 获取请求参数
        std::string title = req.query_param("title");
        std::string content = req.query_param("description");
        std::string category = req.query_param("category");
        std::string status = req.query_param("status");
        std::string publishDate = req.query_param("publishDate");

        // 参数验证
        if (title.empty()) {
            res.error(400, "Title is required");
            return;
        }
        if (content.empty()) {
            res.error(400, "Content is required");
            return;
        }
        if (category.empty()) {
            res.error(400, "Category is required");
            return;
        }

        // 创建游戏对象
        Game game;
        game.title = title;
        game.content = content;
        game.role = category;
        
        // 设置状态，默认为草稿
        if (status == "已发布") {
            game.status = "published";
        } else {
            game.status = "draft";
        }

        // 设置发布日期
        game.publicTime = publishDate;

        // 保存到数据库
        if (game.save()) {
            std::map<std::string, JsonValue> resMp;
            resMp["StatusCode"] = JsonValue(200);
            res.success(resMp);
        } else {
            res.error(500, "Failed to add game content");
        }
    } catch (const std::exception& e) {
        res.error(400, "Invalid request: " + std::string(e.what()));
    }
}

void deleteGameContent(const Request& req, Response& res) {
    if (! Middleware::requiredContent(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    try {
        // 获取游戏ID
        std::string id = req.query_param("id");

        // 验证ID
        if (id.empty()) {
            res.error(400, "Game ID is required");
            return;
        }

        // 检查游戏是否存在
        std::string checkSql = "SELECT id FROM games WHERE id = '" + Model::escapeSqlLiteral(id) + "';";
        auto checkResult = DBConnector::getInstance()->query(checkSql);
        if (checkResult.empty()) {
            res.error(404, "Game not found");
            return;
        }

        // 执行删除
        std::string deleteSql = "DELETE FROM games WHERE id = '" + Model::escapeSqlLiteral(id) + "';";
        int executeCode = DBConnector::getInstance()->execute(deleteSql);

        if (executeCode != -1) {
            std::map<std::string, JsonValue> resMp;
            resMp["StatusCode"] = JsonValue(200);
            resMp["Success"] = JsonValue(true);
            res.json(toJson(resMp));
        } else {
            res.error(500, "Failed to delete game content");
        }
    } catch (const std::exception& e) {
        res.error(400, "Invalid request: " + std::string(e.what()));
    }
}

void updateGameContent(const Request& req, Response& res) {
    if (! Middleware::requiredContent(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }

    try {
        // 获取请求参数
        std::string id = req.query_param("id");
        std::string title = req.query_param("title");
        std::string content = req.query_param("content");
        std::string category = req.query_param("category");
        std::string status = req.query_param("status");
        std::string publishDate = req.query_param("publishDate");

        // 验证ID
        if (id.empty()) {
            res.error(400, "Game ID is required");
            return;
        }

        // 检查游戏是否存在
        std::string checkSql = "SELECT id FROM games WHERE id = '" + Model::escapeSqlLiteral(id) + "';";
        auto checkResult = DBConnector::getInstance()->query(checkSql);
        if (checkResult.empty()) {
            res.error(404, "Game not found");
            return;
        }

        if (status=="已发布") {
            status = "published";
        } else {
            status = "draft";
        }

        // 构建更新字段
        std::vector<std::string> updates;
        if (!title.empty()) updates.push_back("title = '" + Model::escapeSqlLiteral(title) + "'");
        if (!content.empty()) updates.push_back("content = '" + Model::escapeSqlLiteral(content) + "'");
        if (!category.empty()) updates.push_back("role = '" + Model::escapeSqlLiteral(category) + "'");
        if (!status.empty()) updates.push_back("status = '" + Model::escapeSqlLiteral(status) + "'");
        if (!publishDate.empty()) updates.push_back("publicTime = '" + Model::escapeSqlLiteral(publishDate) + "'");

        // 添加更新时间
        std::string currentTime = getFormattedDateTime();
//        std::cout<<currentTime<<std::endl;
        updates.push_back("updatedAt = '" + currentTime + "'");

        if (updates.empty()) {
            res.error(400, "No fields to update");
            return;
        }

        // 构建更新SQL
        std::string updateSql = "UPDATE games SET " + updates[0];
        for (size_t i = 1; i < updates.size(); i++) {
            updateSql += ", " + updates[i];
        }
        updateSql += " WHERE id = '" + Model::escapeSqlLiteral(id) + "';";

        // 执行更新
        int executeCode = DBConnector::getInstance()->execute(updateSql);
        if (executeCode != -1) {
            std::map<std::string, JsonValue> resMp;
            resMp["StatusCode"] = JsonValue(200);
            resMp["Success"] = JsonValue(true);
            res.json(toJson(resMp));
        } else {
            res.error(500, "Failed to update game content");
        }
    } catch (const std::exception& e) {
        res.error(400, "Invalid request: " + std::string(e.what()));
    }
}

//type Request struct {
//    // 搜索关键词，用于模糊匹配公告标题
//    Keyword                             *string `json:"keyword,omitempty"`
//    // 页码，从1开始
//    Page                                string  `json:"page"`
//    // 每页显示的数据条数
//    PageSize                            string  `json:"pageSize"`
//    // 公告状态筛选（如："已发布"、"草稿"、"已过期"和“全部状态”）
//    Status                              string  `json:"status"`
//}

//type Response struct {
//    Data    Data `json:"data"`
//    Success bool `json:"success"`
//}
//
//        type Data struct {
//    List  []List `json:"list"`
//    Total int64  `json:"total"`
//}
//
//        type List struct {
//    Content     *string `json:"content,omitempty"`
//    ExpireDate  *string `json:"expireDate,omitempty"`
//    ID          *string `json:"id,omitempty"`
//    PublishDate *string `json:"publishDate,omitempty"`
//    Status      *string `json:"status,omitempty"`
//    Title       *string `json:"title,omitempty"`
//}

void getAnnouncement(const Request& req, Response& res) {
    if (! Middleware::requiredContent(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
    // 获取查询参数
    std::string keyword = req.query_param("keyword");
    std::string page = req.query_param("Page");
    std::string pageSize = req.query_param("PageSize");
    std::string status = req.query_param("Status");

    // 设置默认分页参数
    int pageNum = 1;
    int pageSizeNum = 10;

    // 解析页码参数
    if (!page.empty()) {
        try {
            pageNum = std::stoi(page);
            if (pageNum < 1) pageNum = 1;
        } catch (...) {
            pageNum = 1;
        }
    }

    // 解析每页数量参数（支持10,20,50）
    if (!pageSize.empty()) {
        try {
            pageSizeNum = std::stoi(pageSize);
            if (pageSizeNum != 10 && pageSizeNum != 20 && pageSizeNum != 50) {
                pageSizeNum = 10;
            }
        } catch (...) {
            pageSizeNum = 10;
        }
    }

    int offset = (pageNum - 1) * pageSizeNum;

    // 构建SQL查询条件
    std::string sqlConditions = "1=1";


    // 关键词搜索
    if (!keyword.empty()) {
        sqlConditions += " AND title LIKE '%" + Model::escapeSqlLiteral(keyword) + "%'";
    }

    // 状态筛选
    if (!status.empty() && status != "全部") {
        if (status == "已发布") {
            sqlConditions += " AND status = 'published'";
        } else if (status == "草稿") {
            sqlConditions += " AND status = 'draft'";
        } else if (status == "已过期") {
            sqlConditions += " AND status = 'unpublished'";
        }
    }

    // 获取总数
    std::string countSql = "SELECT COUNT(*) AS total FROM notifications WHERE " + sqlConditions + ";";
    auto countResult = DBConnector::getInstance()->query(countSql);
    int total = 0;
    if (!countResult.empty()) {
        try {
            total = std::stoll(countResult[0]["total"]);
        } catch (...) {
            total = 0;
        }
    }

    // 获取分页数据
    std::string sql = "SELECT id, title, status, expireDate, publicTime "
                      "FROM notifications WHERE " + sqlConditions +
                      " ORDER BY createdAt DESC LIMIT " + std::to_string(pageSizeNum) +
                      " OFFSET " + std::to_string(offset) + ";";

    auto result = DBConnector::getInstance()->query(sql);

    // 构建响应数据
    std::vector<JsonValue> list;
    for (auto& row : result) {
        std::map<std::string, JsonValue> item;
        if (row.count("id")) item["ID"] = JsonValue(row["id"]);
        if (row.count("title")) item["Title"] = JsonValue(row["title"]);

        // 转换状态显示
        if (row.count("status")) {
            std::string statusText = row["status"];
            if (statusText == "published") statusText = "已发布";
            else if (statusText == "draft") statusText = "草稿";
            else if (statusText == "unpublished") statusText = "已过期";
            item["Status"] = JsonValue(statusText);
        }

        if (row.count("expireDate")) item["expireDate"] = JsonValue(row["expireDate"]);
        if (row.count("publicTime")) item["publishDate"] = JsonValue(row["publicTime"]);
        list.push_back(JsonValue(item));
    }

    // 构建嵌套的响应结构
    std::map<std::string, JsonValue> data;
    data["list"] = JsonValue(list);
    data["total"] = JsonValue(total);

    std::map<std::string, JsonValue> resMp;
    resMp["Data"] = JsonValue(data);
    resMp["StatusCode"] = JsonValue(200);
    resMp["Success"] = JsonValue(true);

    res.json(toJson(resMp));
}

void addAnnouncement(const Request& req, Response& res) {
    if (! Middleware::requiredContent(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
    try {
        // 获取请求参数
        std::string title = req.query_param("title");
        std::string content = req.query_param("content");
        std::string status = req.query_param("status");
        std::string publishDate = req.query_param("publishDate");
        std::string expireDate = req.query_param("expireDate");

        // 参数验证
        if (title.empty()) {
            res.error(400, "Title is required");
            return;
        }
        if (content.empty()) {
            res.error(400, "Content is required");
            return;
        }

        if (status.empty()) {
            res.error(400, "Status is required");
            return;
        }

        if (publishDate.empty()) {
            res.error(400, "PublishDate is required");
            return;
        }

        // 创建游戏对象
        Notification notification;
        notification.title = title;
        notification.content = content;
        notification.expireDate = expireDate;
        notification.publicTime = publishDate;

        // 设置状态，默认为草稿
        if (status == "已发布") {
            notification.status = "published";
        } else if (status == "已过期") {
            notification.status = "unpublished";
        } else {
            notification.status = "draft";
        }

        // 保存到数据库
        if (notification.save()) {
            std::map<std::string, JsonValue> resMp;
            resMp["StatusCode"] = JsonValue(200);
            res.success(resMp);
        } else {
            res.error(500, "Failed to add content");
        }
    } catch (const std::exception& e) {
        res.error(400, "Invalid request: " + std::string(e.what()));
    }
}

void deleteAnnouncement(const Request& req, Response& res) {
    if (! Middleware::requiredContent(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
    try {
        // 获取游戏ID
        std::string id = req.query_param("id");

        // 验证ID
        if (id.empty()) {
            res.error(400, "ID is required");
            return;
        }

        // 检查游戏是否存在
        std::string checkSql = "SELECT id FROM notifications WHERE id = '" + Model::escapeSqlLiteral(id) + "';";
        auto checkResult = DBConnector::getInstance()->query(checkSql);
        if (checkResult.empty()) {
            res.error(404, "not found");
            return;
        }

        // 执行删除
        std::string deleteSql = "DELETE FROM notifications WHERE id = '" + Model::escapeSqlLiteral(id) + "';";
        int executeCode = DBConnector::getInstance()->execute(deleteSql);

        if (executeCode != -1) {
            std::map<std::string, JsonValue> resMp;
            resMp["StatusCode"] = JsonValue(200);
            resMp["Success"] = JsonValue(true);
            res.json(toJson(resMp));
        } else {
            res.error(500, "Failed to delete content");
        }
    } catch (const std::exception& e) {
        res.error(400, "Invalid request: " + std::string(e.what()));
    }
}

void updateAnnouncement(const Request& req, Response& res) {
    if (! Middleware::requiredContent(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
    try {
        // 获取请求参数
        std::string id = req.query_param("id");
        std::string title = req.query_param("title");
        std::string content = req.query_param("content");
        std::string status = req.query_param("status");
        std::string publishDate = req.query_param("publishDate");
        std::string expireDate = req.query_param("expireDate");

        // 验证ID
        if (id.empty()) {
            res.error(400, "ID is required");
            return;
        }

        // 检查游戏是否存在
        std::string checkSql = "SELECT id FROM notifications WHERE id = '" + Model::escapeSqlLiteral(id) + "';";
        auto checkResult = DBConnector::getInstance()->query(checkSql);
        if (checkResult.empty()) {
            res.error(404, "not found");
            return;
        }

        if (status == "已发布") {
            status = "published";
        } else if (status == "草稿") {
            status = "draft";
        } else if (status == "已过期") {
            status = "unpublished";
        }

        // 构建更新字段
        std::vector<std::string> updates;
        if (!title.empty()) updates.push_back("title = '" + Model::escapeSqlLiteral(title) + "'");
        if (!content.empty()) updates.push_back("content = '" + Model::escapeSqlLiteral(content) + "'");
        if (!status.empty()) updates.push_back("status = '" + Model::escapeSqlLiteral(status) + "'");
        if (!publishDate.empty()) updates.push_back("publicTime = '" + Model::escapeSqlLiteral(publishDate) + "'");
        if (!expireDate.empty()) updates.push_back("expireDate = '" + Model::escapeSqlLiteral(expireDate) + "'");

        // 添加更新时间
        std::string currentTime = getFormattedDateTime();
//        std::cout<<currentTime<<std::endl;
        updates.push_back("updatedAt = '" + currentTime + "'");

        if (updates.empty()) {
            res.error(400, "No fields to update");
            return;
        }

        // 构建更新SQL
        std::string updateSql = "UPDATE notifications SET " + updates[0];
        for (size_t i = 1; i < updates.size(); i++) {
            updateSql += ", " + updates[i];
        }
        updateSql += " WHERE id = '" + Model::escapeSqlLiteral(id) + "';";

        // 执行更新
        int executeCode = DBConnector::getInstance()->execute(updateSql);
        if (executeCode != -1) {
            std::map<std::string, JsonValue> resMp;
            resMp["StatusCode"] = JsonValue(200);
            resMp["Success"] = JsonValue(true);
            res.json(toJson(resMp));
        } else {
            res.error(500, "Failed to update content");
        }
    } catch (const std::exception& e) {
        res.error(400, "Invalid request: " + std::string(e.what()));
    }
}

void getAccountsPaginated(const Request& req, Response& res) {
    if (! Middleware::requiredContent(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
    res.success();
}

void addAccount(const Request& req, Response& res) {
    if (! Middleware::requiredContent(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
    res.success();
}

void updateUser(const Request& req, Response& res) {
    if (! Middleware::requiredContent(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
    res.success();
}

void deleteUser(const Request& req, Response& res) {
    if (! Middleware::requiredContent(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
    res.success();
}

void getLogsPaginated(const Request& req, Response& res) {
    if (! Middleware::requiredContent(req)) {
        res.error(401, "Permission denied due to insufficient privileges");
        return;
    }
    res.success();
}